// index.js
import { createRouter, createWebHistory } from 'vue-router'
import Layout from '../layouts/Layout.vue'
import { ElMessage } from 'element-plus'

// 页面
import LoginPage from '../views/LoginPage.vue'
import RegisterPage from '../views/RegisterPage.vue'
import CustomerPage from '../views/CustomerPage.vue'
import CartPage from '../views/CartPage.vue'
import OrderPage from '../views/OrderPage.vue'
import AdminPage from '../views/AdminPage.vue'
import BossPage from '../views/BossPage.vue'

const routes = [
  { path: '/login', name: 'Login', component: LoginPage },
  { path: '/register', name: 'Register', component: RegisterPage },
  {
    path: '/',
    component: Layout,
    redirect: '/customer',
    children: [
      { path: 'customer', name: 'Customer', component: CustomerPage },
      { path: 'cart', name: 'Cart', component: CartPage },
      { path: 'orders', name: 'Orders', component: OrderPage },
      { path: 'admin', name: 'Admin', component: AdminPage },
      { path: 'boss', name: 'Boss', component: BossPage }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const publicPages = ['/login', '/register'] // 不需要登录的页面
  const authRequired = !publicPages.includes(to.path)
  const employeeId = localStorage.getItem('employeeId')

  if (authRequired && !employeeId) {
    localStorage.removeItem('employeeId')
    localStorage.removeItem('storeId')
    ElMessage.warning('请先登录')
    next('/login')
  } else {
    next()
  }
})

export default router
